package cn.com.homeyoda.aimate.aihealth.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.com.homeyoda.aimate.aihealth.ui.bluetooth.BluetoothMatchBean;


public class JsonFileManager {
    private static final Gson gson = new Gson();
    private static final Type PERSON_LIST_TYPE = new TypeToken<List<BluetoothMatchBean>>(){}.getType();
    private Context context;
    private static final String BASE_DIR = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/MyApp/";
    public JsonFileManager(Context context) {
        this.context = context;
    }
    private File getPrivateFile(String fileName) {
        return new File(context.getFilesDir(), fileName);
    }
    /**
     * 读取列表
     */
    public static List<BluetoothMatchBean> readList(String filePath) {
        File file = new File(BASE_DIR+filePath);
        File parentDir = file.getParentFile(); // 获取父目录对象，即 MyApp 文件夹

        // 检查父目录是否存在，如果不存在则创建它
        if (parentDir != null && !parentDir.exists()) {
            if (parentDir.mkdirs()) {
                Log.i("huahua", "目录创建成功");
            } else {
                Log.i("huahua", "目录创建失败");
            }
        }
        if (!file.exists() || file.length() == 0) {
            return new ArrayList<>();
        }

        try (FileReader reader = new FileReader(file)) {
            List<BluetoothMatchBean> persons = gson.fromJson(reader, PERSON_LIST_TYPE);
            return persons != null ? persons : new ArrayList<>();
        } catch (Exception e) {
            Log.i("huahua","读取失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 保存列表（覆盖写入）
     */
    public static void saveList(String filePath, List<BluetoothMatchBean> persons) {
        try (FileWriter writer = new FileWriter(BASE_DIR+filePath)) {
            gson.toJson(persons, writer);
            Log.i("huahua","成功保存 " + persons.size() + " 条数据");
        } catch (Exception e) {
            Log.i("huahua","保存失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 追加数据到列表
     */
    public static void appendToList(String filePath, BluetoothMatchBean newPerson) {
        // 1. 先读取现有数据
        List<BluetoothMatchBean> persons = readList(filePath);

        // 2. 添加新数据
        persons.add(newPerson);

        // 3. 重新保存完整列表
        saveList(filePath, persons);
    }
}
